package com.wss.autodeliver.rest;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.converters.Auto;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/autodeliver")
public class AutodeliverController {


    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/checkState/{userId}")
    public Integer findResumeOpenState(@PathVariable Long userId) {
        Integer forObject =
                restTemplate.getForObject("http://localhost:8080/resume/openstate/"
                        + userId, Integer.class);
        System.out.println("======>>>调⽤简历微服务，获取到⽤户" +
                userId + "的默认简历当前状态为：" + forObject);
        return forObject;
    }

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("getPort")
    public String getPort(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("lagou-service-resume");
        ServiceInstance instance = instanceList.get(1);
        String host = instance.getHost();
        int port = instance.getPort();
        String url="http://"+host+":"+port+"/resume/getPort/";
        String object = restTemplate.getForObject(url, String.class);
        System.out.println(object);
        return  object;
    }


    @GetMapping("getPortLoad")
    public String getPortLoad(){
        String url="http://lagou-service-resume/resume/getPort/";
        String object = restTemplate.getForObject(url, String.class);
        System.out.println(object);
        return  object;
    }


    /**
     * 提供者模拟处理超时，调用方法添加Hystrix控制
     * @param
     * @return
     */
    // 使用@HystrixCommand注解进行熔断控制
    @HystrixCommand(
            // 线程池标识，要保持唯一，不唯一的话就共用了
            threadPoolKey = "findResumeOpenStateTimeout",
            // 线程池细节属性配置
            threadPoolProperties = {
                    @HystrixProperty(name="coreSize",value = "1"), // 线程数
                    @HystrixProperty(name="maxQueueSize",value="20") // 等待队列长度
            },
            // commandProperties熔断的一些细节属性配置
            commandProperties = {
                    // 每一个属性都是一个HystrixProperty
                    @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
            }
    )
    @GetMapping("getPortLoadByHystrix")
    public String getPortLoadByHystrix(){
        String url="http://lagou-service-resume/resume/getPortLoadByHystrix/";
        String object = restTemplate.getForObject(url, String.class);
        System.out.println(object);
        return  object;
    }

    @GetMapping("getPortLoadByHystrixFallback")
    @HystrixCommand(
            // 线程池标识，要保持唯一，不唯一的话就共用了
            threadPoolKey = "findResumeOpenStateTimeoutFallback",
            // 线程池细节属性配置
            threadPoolProperties = {
                    @HystrixProperty(name="coreSize",value = "2"), // 线程数
                    @HystrixProperty(name="maxQueueSize",value="20") // 等待队列长度
            },
            // commandProperties熔断的一些细节属性配置
            commandProperties = {
                    // 每一个属性都是一个HystrixProperty
                    @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
                    // hystrix高级配置，定制工作过程细节
                    ,
                    // 8秒钟内，请求次数达到2个，并且失败率在50%以上，就跳闸跳闸后活动窗⼝设置为3s
                    // 统计时间窗口定义
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "8000"),
                    // 统计时间窗口内的最小请求数
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "2"),
                    // 统计时间窗口内的错误数量百分比阈值
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
                    // 自我修复时的活动窗口长度
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "3000")
            },
            fallbackMethod = "myFallBack"  // 回退方法
    )
    public String getPortLoadByHystrixFallback(){
        String url="http://lagou-service-resume/resume/getPortLoadByHystrix/";
        String object = restTemplate.getForObject(url, String.class);
        System.out.println(object);
        return  object;
    }

    /*
      定义回退方法，返回预设默认值
      注意：该方法形参和返回值与原始方法保持一致
   */
    public String myFallBack( ) {
        return "8888"; // 兜底数据
    }
}
